﻿using System;
using System.Linq;
using Abp.Domain.Repositories;
using Abp.Runtime.Session;
using Hicap.AuthorizationServer.Core.Caches.Sys;
using Hicap.AuthorizationServer.Core.Caches.Sys.Interface;
using Hicap.AuthorizationServer.Core.Models.Sys;

namespace Hicap.AuthorizationServer.Core.Domains.Authorization
{
    public class PermissionCheckerManager : AuthorizationServerDomainServiceBase, IPermissionCheckerManager
    {
        private const string CacheName = "UserAuthCache";
        private readonly IRepository<UserRoleRelated> _userRoleRepository;
        private readonly IRepository<AuthObjectRoleRelated> _authRoleRepository;
        private readonly IAbpSession _abpSession;
        private readonly IUserAuthCache _userAuthCache;
        private readonly IUserCache _userCache;

        /// <summary>
        /// Catagory的构造方法
        /// </summary>
        public PermissionCheckerManager(IRepository<UserRoleRelated> userRoleRepository,
            IRepository<AuthObjectRoleRelated> authRoleRepository,
            IAbpSession abpSession,
            IUserAuthCache userAuthCache, IUserCache userCache)
        {
            _userRoleRepository = userRoleRepository;
            _authRoleRepository = authRoleRepository;
            _abpSession = abpSession;
            _userAuthCache = userAuthCache;
            _userCache = userCache;
        }

        public bool CheckPermission(string authObject)
        {
            var userId = Convert.ToInt32(_abpSession.UserId.Value);
            var userAuth = _userAuthCache.Get(userId);
            return userAuth.AuthObjects.Select(x => x.ObjectCode).Contains(authObject);
        }
    }
}